<?php
/**
 * @version		$Id: article.php 11253 2008-11-10 23:38:48Z ircmaxell $
 * @package		Joomla
 * @subpackage	Content
 * @copyright	Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
 * @license		GNU/GPL, see LICENSE.php
 * Joomla! is free software. This version may have been modified pursuant to the
 * GNU General Public License, and as distributed it includes or is derivative
 * of works licensed under the GNU General Public License or other free or open
 * source software licenses. See COPYRIGHT.php for copyright notices and
 * details.
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );

jimport('joomla.application.component.model');

/**
 * Content Component Article Model
 *
 * @package		Joomla
 * @subpackage	Content
 * @since 1.5
 */
class NewsletterModelNewsletter extends JModel
{
	var $_article = null;
	var $_body = null;
	/* repositorios para resolv */
	var $noticiaDelDia = array(); #array('Titulo'=>'Una noticia de prueba', 'URL'=>'', 'Texto'=>'Aquí me pongo a cantar, al compás de la vihuela, que al hombre que lo desvela una pena extraordinaria, con el cantar se consuela.');
	var $grafica = array();
	/*array(
			array('Titulo'=>'Grafica 1', 'URL'=>'grafica-1'),
			array('Titulo'=>'Grafica 2', 'URL'=>'grafica-2'),
			array('Titulo'=>'Grafica 3', 'URL'=>'grafica-3')
	);*/
	var $portal = array();
	/* array(
			array('Titulo'=>'Portal 1', 'URL'=>'portal-1'),
			array('Titulo'=>'Portal 2', 'URL'=>'portal-2'),
			array('Titulo'=>'Portal 3', 'URL'=>'portal-3')
	); */
	var $radio =  array();
	/*array(
			array('Titulo'=>'Radio 1', 'URL'=>'radio-1'),
	); */
	var $television =  array();
	/*array(
			array('Titulo'=>'Television 1', 'URL'=>'television-1'),
	); */
	var $agencia = array();
	/*array(
			array('Titulo'=>'Agencia de Noticias 1', 'URL'=>'agencia-de-noticias-1'),
			array('Titulo'=>'Agencia de Noticias 2', 'URL'=>'agencia-de-noticias-2'),
			array('Titulo'=>'Agencia de Noticias 3', 'URL'=>'agencia-de-noticias-3')
	); */
	var $recomendadas = array();
	var $tapas        = array();
	
	function __construct()
	{
		parent::__construct();

	}

	function setBody($body) {
		$this->_body = $body;
	}
	
	function getBody() {
		return $this->_body;
	}
	
	function getList(&$params)
	{
		global $mainframe;

		$db		=& $this->_db;
		$user		=& JFactory::getUser();
		$userId		= (int) $user->get('id');

		#$count		= (int) $params->get('count', 5);
		$catid		= trim( $params->get('catid') );
		$secid		= trim( $params->get('secid') );
		$show_front	= $params->get('show_front', 1);
		$aid		= $user->get('aid', 0);

		$contentConfig = &JComponentHelper::getParams( 'com_content' );
		$access		= !$contentConfig->get('show_noauth');

		$nullDate	= $db->getNullDate();

		$date =& JFactory::getDate();
		$now = $date->toMySQL();

		$where		= 'a.state = 1'
			. ' AND ( a.publish_up = '.$db->Quote($nullDate).' OR a.publish_up <= '.$db->Quote($now).' )'
			. ' AND ( a.publish_down = '.$db->Quote($nullDate).' OR a.publish_down >= '.$db->Quote($now).' )'
			;

		// User Filter
		switch ($params->get( 'user_id' ))
		{
			case 'by_me':
				$where .= ' AND (created_by = ' . (int) $userId . ' OR modified_by = ' . (int) $userId . ')';
				break;
			case 'not_me':
				$where .= ' AND (created_by <> ' . (int) $userId . ' AND modified_by <> ' . (int) $userId . ')';
				break;
		}

		// Ordering
		switch ($params->get( 'ordering' ))
		{
			case 'm_dsc':
				$ordering		= 'a.modified DESC, a.created DESC';
				break;
			case 'c_dsc':
			default:
				$ordering		= 'a.created DESC';
				break;
		}

		if ($catid)
		{
			$ids = explode( ',', $catid );
			JArrayHelper::toInteger( $ids );
			$catCondition = ' AND (cc.id=' . implode( ' OR cc.id=', $ids ) . ')';
		}
		if ($secid)
		{
			$ids = explode( ',', $secid );
			JArrayHelper::toInteger( $ids );
			$secCondition = ' AND (s.id=' . implode( ' OR s.id=', $ids ) . ')';
		}

		// Content Items only
		$query = 'SELECT a.id, a.title, ' .
			' med.title as medio, prog.title as programa, area.title as area, a.es_anticipo, a.es_recomendada, a.es_institucional, a.valoracion, provincia.title as provincia, cc.title as category, '.
			' CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(":", a.id, a.alias) ELSE a.id END as slug,'.
			' CASE WHEN CHAR_LENGTH(cc.alias) THEN CONCAT_WS(":", cc.id, cc.alias) ELSE cc.id END as catslug'.
			' FROM #__content AS a' .
			($show_front == '0' ? ' LEFT JOIN #__content_frontpage AS f ON f.content_id = a.id' : '') .
			' INNER JOIN #__categories AS cc ON cc.id = a.catid' .
			' INNER JOIN #__sections AS s ON s.id = a.sectionid' .
			' LEFT JOIN #__medio AS med ON a.medid = med.id'.
			' LEFT JOIN #__programa AS prog ON a.progid = prog.id'.
			' LEFT JOIN #__area AS area ON a.areaid = area.id'.
			' LEFT JOIN #__area AS provincia ON a.provinciaid = provincia.id'.
			' WHERE '. $where .' AND s.id > 0' .
			($access ? ' AND a.access <= ' .(int) $aid. ' AND cc.access <= ' .(int) $aid. ' AND s.access <= ' .(int) $aid : '').
			($catid ? $catCondition : '').
			($secid ? $secCondition : '').
			($show_front == '0' ? ' AND f.content_id IS NULL ' : '').
			' AND s.published = 1' .
			' AND cc.published = 1' .
			' AND a.es_anticipo = 0 '.
			' AND DATEDIFF(CURDATE(),date(created))<2'. 
			' AND a.es_recomendada = 0'.
			' AND cc.id != ' . TAPAS_CATEGORY_ID .
			' ORDER BY '. $ordering.
			' LIMIT 200';
		
		$db->setQuery($query, 0, $count);
		$rows = $db->loadObjectList();

		return $rows;
	}

	function findTitulares($catid, $cuantas = 10)
	{
		$db               = & $this->_db;
		$noticiaDelDiaId  = JRequest::getInt('noticiaDelDia');

		$query	= 'SELECT a.id, a.title Titulo, '.
				' CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(":", a.id, a.alias) ELSE a.id END as slug,'.
				' CASE WHEN CHAR_LENGTH(cc.alias) THEN CONCAT_WS(":", cc.id, cc.alias) ELSE cc.id END as catslug'.
				' FROM #__content a' .
				' INNER JOIN #__categories AS cc ON cc.id = a.catid' .
				' INNER JOIN #__sections AS s ON s.id = a.sectionid' .
				' WHERE a.id != '          .$noticiaDelDiaId.
				' AND a.catid = '    .$catid.
				' AND s.published = 1' .
				' AND cc.published = 1' .
				' AND a.es_recomendada = 0'.
				' ORDER BY created DESC '.
				' LIMIT '                  .$cuantas;
		$db->setQuery($query);
		$rows = $db->loadObjectList();
		foreach ($rows as $article)
			$article->URL = JURI::base().ContentHelperRoute::getArticleRoute($article->slug, $article->catslug, $article->sectionid);
		return $rows;
	}	

	function findNoticiaDelDia()
	{
		$db               = & $this->_db;
		$articleid 	= JRequest::getInt('noticiaDelDia');


		$query	= 'SELECT a.id, a.title Titulo, a.introtext Texto, '.
				' CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(":", a.id, a.alias) ELSE a.id END as slug,'.
				' CASE WHEN CHAR_LENGTH(cc.alias) THEN CONCAT_WS(":", cc.id, cc.alias) ELSE cc.id END as catslug'.
				' FROM #__content a' .
				' INNER JOIN #__categories AS cc ON cc.id = a.catid' .
				' INNER JOIN #__sections AS s ON s.id = a.sectionid' .
				' WHERE a.id = '.$articleid;
		$db->setQuery($query);
		$rows = $db->loadObjectList();
		$article = $rows[0];

		$article->URL = JURI::base().ContentHelperRoute::getArticleRoute($article->slug, $article->catslug, $article->sectionid);
		return $article;
	}

	function findRecomendadas($cuantas) {
		return array($cuantas);
	}

	function findTapas($cuantas) {
		return array($cuantas);
	}

	function _resolve($objeto, $posicion, $atributo) {
		if (!empty($objeto)) {
			$obj = $this->$objeto;
			if (empty($posicion)) {
				if (empty($atributo)) 
					return var_dump($obj);
				return $obj->$atributo;
			} else {
				if (empty($atributo)) 
					return var_dump($obj);
				$elem = $obj[$posicion - 1];
				return $elem->$atributo;
			}
		}
	}    

	function compilar() {
		$template = file_get_contents(PATH_PLANTILLAS.DS."newsletter.html");

		$tokens = array();
		preg_match_all("/\Q$\E(\w+)(\[(\d)\])?(\.(\w+))?/", $template, $tokens);
		$valores = array();
		$this->noticiaDelDia =& $this->findNoticiaDelDia();

		$this->grafica       =& $this->findTitulares(37,3);
		$this->portal        =& $this->findTitulares(31,3);
		$this->radio         =& $this->findTitulares(14,1);
		$this->television    =& $this->findTitulares(19,1);
		$this->agencia       =& $this->findTitulares(18,2);
		$this->recomendadas  =& $this->findRecomendadas(5);
		$this->tapas         =& $this->findTapas(4);

		for ($i=0; $i < count($tokens[0]); ++$i) {
			$valores[$tokens[0][$i]] = $this->_resolve($tokens[1][$i], $tokens[3][$i], $tokens[5][$i]);
		}

		$this->_body = $template;
		foreach ($valores as $token => $valor) {
			$this->_body = str_replace($token, $valor, $this->_body);
		}
	}

}
?>